<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html 
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <title>Module: ActiveRecord::Associations::ClassMethods</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />
  <script type="text/javascript">
  // <![CDATA[

  function popupCode( url ) {
    window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400")
  }

  function toggleCode( id ) {
    if ( document.getElementById )
      elem = document.getElementById( id );
    else if ( document.all )
      elem = eval( "document.all." + id );
    else
      return false;

    elemStyle = elem.style;
    
    if ( elemStyle.display != "block" ) {
      elemStyle.display = "block"
    } else {
      elemStyle.display = "none"
    }

    return true;
  }
  
  // Make codeblocks hidden by default
  document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" )
  
  // ]]>
  </script>

</head>
<body>



    <div id="classHeader">
        <table class="header-table">
        <tr class="top-aligned-row">
          <td><strong>Module</strong></td>
          <td class="class-name-in-header">ActiveRecord::Associations::ClassMethods</td>
        </tr>
        <tr class="top-aligned-row">
            <td><strong>In:</strong></td>
            <td>
                <a href="../../../files/vendor/rails/activerecord/lib/active_record/associations_rb.html">
                vendor/rails/activerecord/lib/active_record/associations.rb
                </a>
        <br />
            </td>
        </tr>

        </table>
    </div>
  <!-- banner header -->

  <div id="bodyContent">



  <div id="contextContent">

    <div id="description">
      <p>
Associations are a set of macro-like class methods for tying objects
together through foreign keys. They express relationships like
&quot;Project has one Project Manager&quot; or &quot;Project belongs to a
Portfolio&quot;. Each macro adds a number of methods to the class which are
specialized according to the collection or association symbol and the
options hash. It works much the same way as Ruby&#8216;s own <tt>attr*</tt>
methods. Example:
</p>
<pre>
  class Project &lt; ActiveRecord::Base
    belongs_to              :portfolio
    has_one                 :project_manager
    has_many                :milestones
    has_and_belongs_to_many :categories
  end
</pre>
<p>
The project class now has the following methods (and more) to ease the
traversal and manipulation of its relationships:
</p>
<ul>
<li><tt>Project#portfolio, Project#portfolio=(portfolio),
Project#portfolio.nil?</tt>

</li>
<li><tt>Project#project_manager, Project#project_manager=(project_manager),
Project#project_manager.nil?,</tt>

</li>
<li><tt>Project#milestones.empty?, Project#milestones.size, Project#milestones,
Project#milestones&lt;&lt;(milestone),</tt>
<tt>Project#milestones.delete(milestone),
Project#milestones.find(milestone_id), Project#milestones.find(:all,
options),</tt> <tt>Project#milestones.build, Project#milestones.create</tt>

</li>
<li><tt>Project#categories.empty?, Project#categories.size, Project#categories,
Project#categories&lt;&lt;(category1),</tt>
<tt>Project#categories.delete(category1)</tt>

</li>
</ul>
<h3>A word of warning</h3>
<p>
Don&#8216;t create associations that have the same name as instance methods
of <a href="../Base.html">ActiveRecord::Base</a>. Since the association
adds a method with that name to its model, it will override the inherited
method and break things. For instance, attributes and connection would be
bad choices for association names.
</p>
<h2>Auto-generated methods</h2>
<h3>Singular associations (one-to-one)</h3>
<pre>
                                    |            |  belongs_to  |
  generated methods                 | belongs_to | :polymorphic | has_one
  ----------------------------------+------------+--------------+---------
  #other                            |     X      |      X       |    X
  #other=(other)                    |     X      |      X       |    X
  #build_other(attributes={})       |     X      |              |    X
  #create_other(attributes={})      |     X      |              |    X
  #other.create!(attributes={})     |            |              |    X
  #other.nil?                       |     X      |      X       |
</pre>
<h3>Collection associations (one-to-many / many-to-many)</h3>
<pre>
                                    |       |          | has_many
  generated methods                 | habtm | has_many | :through
  ----------------------------------+-------+----------+----------
  #others                           |   X   |    X     |    X
  #others=(other,other,...)         |   X   |    X     |
  #other_ids                        |   X   |    X     |    X
  #other_ids=(id,id,...)            |   X   |    X     |
  #others&lt;&lt;                         |   X   |    X     |    X
  #others.push                      |   X   |    X     |    X
  #others.concat                    |   X   |    X     |    X
  #others.build(attributes={})      |   X   |    X     |    X
  #others.create(attributes={})     |   X   |    X     |
  #others.create!(attributes={})    |   X   |    X     |    X
  #others.size                      |   X   |    X     |    X
  #others.length                    |   X   |    X     |    X
  #others.count                     |       |    X     |    X
  #others.sum(args*,&amp;block)         |   X   |    X     |    X
  #others.empty?                    |   X   |    X     |    X
  #others.clear                     |   X   |    X     |
  #others.delete(other,other,...)   |   X   |    X     |    X
  #others.delete_all                |   X   |    X     |
  #others.destroy_all               |   X   |    X     |    X
  #others.find(*args)               |   X   |    X     |    X
  #others.find_first                |   X   |          |
  #others.uniq                      |   X   |    X     |
  #others.reset                     |   X   |    X     |    X
</pre>
<h2>Cardinality and associations</h2>
<p>
ActiveRecord associations can be used to describe relations with
one-to-one, one-to-many and many-to-many cardinality. Each model uses an
association to describe its role in the relation. In each case, the <tt><a
href="ClassMethods.html#M001105">belongs_to</a></tt> association is used in
the model that has the foreign key.
</p>
<h3>One-to-one</h3>
<p>
Use <tt><a href="ClassMethods.html#M001104">has_one</a></tt> in the base,
and <tt><a href="ClassMethods.html#M001105">belongs_to</a></tt> in the
associated model.
</p>
<pre>
  class Employee &lt; ActiveRecord::Base
    has_one :office
  end
  class Office &lt; ActiveRecord::Base
    belongs_to :employee    # foreign key - employee_id
  end
</pre>
<h3>One-to-many</h3>
<p>
Use <tt><a href="ClassMethods.html#M001103">has_many</a></tt> in the base,
and <tt><a href="ClassMethods.html#M001105">belongs_to</a></tt> in the
associated model.
</p>
<pre>
  class Manager &lt; ActiveRecord::Base
    has_many :employees
  end
  class Employee &lt; ActiveRecord::Base
    belongs_to :manager     # foreign key - manager_id
  end
</pre>
<h3>Many-to-many</h3>
<p>
There are two ways to build a many-to-many relationship.
</p>
<p>
The first way uses a <tt><a
href="ClassMethods.html#M001103">has_many</a></tt> association with the
<tt>:through</tt> option and a join model, so there are two stages of
associations.
</p>
<pre>
  class Assignment &lt; ActiveRecord::Base
    belongs_to :programmer  # foreign key - programmer_id
    belongs_to :project     # foreign key - project_id
  end
  class Programmer &lt; ActiveRecord::Base
    has_many :assignments
    has_many :projects, :through =&gt; :assignments
  end
  class Project &lt; ActiveRecord::Base
    has_many :assignments
    has_many :programmers, :through =&gt; :assignments
  end
</pre>
<p>
For the second way, use <tt><a
href="ClassMethods.html#M001106">has_and_belongs_to_many</a></tt> in both
models. This requires a join table that has no corresponding model or
primary key.
</p>
<pre>
  class Programmer &lt; ActiveRecord::Base
    has_and_belongs_to_many :projects       # foreign keys in the join table
  end
  class Project &lt; ActiveRecord::Base
    has_and_belongs_to_many :programmers    # foreign keys in the join table
  end
</pre>
<p>
Choosing which way to build a many-to-many relationship is not always
simple. If you need to work with the relationship model as its own entity,
use <tt><a href="ClassMethods.html#M001103">has_many</a> :through</tt>. Use
<tt><a href="ClassMethods.html#M001106">has_and_belongs_to_many</a></tt>
when working with legacy schemas or when you never work directly with the
relationship itself.
</p>
<h2>Is it a <tt><a href="ClassMethods.html#M001105">belongs_to</a></tt> or <tt><a href="ClassMethods.html#M001104">has_one</a></tt> association?</h2>
<p>
Both express a 1-1 relationship. The difference is mostly where to place
the foreign key, which goes on the table for the class declaring the <tt><a
href="ClassMethods.html#M001105">belongs_to</a></tt> relationship. Example:
</p>
<pre>
  class User &lt; ActiveRecord::Base
    # I reference an account.
    belongs_to :account
  end

  class Account &lt; ActiveRecord::Base
    # One user references me.
    has_one :user
  end
</pre>
<p>
The tables for these classes could look something like:
</p>
<pre>
  CREATE TABLE users (
    id int(11) NOT NULL auto_increment,
    account_id int(11) default NULL,
    name varchar default NULL,
    PRIMARY KEY  (id)
  )

  CREATE TABLE accounts (
    id int(11) NOT NULL auto_increment,
    name varchar default NULL,
    PRIMARY KEY  (id)
  )
</pre>
<h2>Unsaved objects and associations</h2>
<p>
You can manipulate objects and associations before they are saved to the
database, but there is some special behavior you should be aware of, mostly
involving the saving of associated objects.
</p>
<h3>One-to-one associations</h3>
<ul>
<li>Assigning an object to a <tt><a
href="ClassMethods.html#M001104">has_one</a></tt> association automatically
saves that object and the object being replaced (if there is one), in order
to update their primary keys - except if the parent object is unsaved
(<tt>new_record? == true</tt>).

</li>
<li>If either of these saves fail (due to one of the objects being invalid) the
assignment statement returns <tt>false</tt> and the assignment is
cancelled.

</li>
<li>If you wish to assign an object to a <tt><a
href="ClassMethods.html#M001104">has_one</a></tt> association without
saving it, use the <tt>association.build</tt> method (documented below).

</li>
<li>Assigning an object to a <tt><a
href="ClassMethods.html#M001105">belongs_to</a></tt> association does not
save the object, since the foreign key field belongs on the parent. It does
not save the parent either.

</li>
</ul>
<h3>Collections</h3>
<ul>
<li>Adding an object to a collection (<tt><a
href="ClassMethods.html#M001103">has_many</a></tt> or <tt><a
href="ClassMethods.html#M001106">has_and_belongs_to_many</a></tt>)
automatically saves that object, except if the parent object (the owner of
the collection) is not yet stored in the database.

</li>
<li>If saving any of the objects being added to a collection (via <tt>push</tt>
or similar) fails, then <tt>push</tt> returns <tt>false</tt>.

</li>
<li>You can add an object to a collection without automatically saving it by
using the <tt>collection.build</tt> method (documented below).

</li>
<li>All unsaved (<tt>new_record? == true</tt>) members of the collection are
automatically saved when the parent is saved.

</li>
</ul>
<h3>Association callbacks</h3>
<p>
Similar to the normal callbacks that hook into the lifecycle of an Active
Record object, you can also define callbacks that get triggered when you
add an object to or remove an object from an association collection.
Example:
</p>
<pre>
  class Project
    has_and_belongs_to_many :developers, :after_add =&gt; :evaluate_velocity

    def evaluate_velocity(developer)
      ...
    end
  end
</pre>
<p>
It&#8216;s possible to stack callbacks by passing them as an array.
Example:
</p>
<pre>
  class Project
    has_and_belongs_to_many :developers, :after_add =&gt; [:evaluate_velocity, Proc.new { |p, d| p.shipping_date = Time.now}]
  end
</pre>
<p>
Possible callbacks are: <tt>before_add</tt>, <tt>after_add</tt>,
<tt>before_remove</tt> and <tt>after_remove</tt>.
</p>
<p>
Should any of the <tt>before_add</tt> callbacks throw an exception, the
object does not get added to the collection. Same with the
<tt>before_remove</tt> callbacks; if an exception is thrown the object
doesn&#8216;t get removed.
</p>
<h3>Association extensions</h3>
<p>
The proxy objects that control the access to associations can be extended
through anonymous modules. This is especially beneficial for adding new
finders, creators, and other factory-type methods that are only used as
part of this association. Example:
</p>
<pre>
  class Account &lt; ActiveRecord::Base
    has_many :people do
      def find_or_create_by_name(name)
        first_name, last_name = name.split(&quot; &quot;, 2)
        find_or_create_by_first_name_and_last_name(first_name, last_name)
      end
    end
  end

  person = Account.find(:first).people.find_or_create_by_name(&quot;David Heinemeier Hansson&quot;)
  person.first_name # =&gt; &quot;David&quot;
  person.last_name  # =&gt; &quot;Heinemeier Hansson&quot;
</pre>
<p>
If you need to share the same extensions between many associations, you can
use a named extension module. Example:
</p>
<pre>
  module FindOrCreateByNameExtension
    def find_or_create_by_name(name)
      first_name, last_name = name.split(&quot; &quot;, 2)
      find_or_create_by_first_name_and_last_name(first_name, last_name)
    end
  end

  class Account &lt; ActiveRecord::Base
    has_many :people, :extend =&gt; FindOrCreateByNameExtension
  end

  class Company &lt; ActiveRecord::Base
    has_many :people, :extend =&gt; FindOrCreateByNameExtension
  end
</pre>
<p>
If you need to use multiple named extension modules, you can specify an
array of modules with the <tt>:extend</tt> option. In the case of name
conflicts between methods in the modules, methods in modules later in the
array supercede those earlier in the array. Example:
</p>
<pre>
  class Account &lt; ActiveRecord::Base
    has_many :people, :extend =&gt; [FindOrCreateByNameExtension, FindRecentExtension]
  end
</pre>
<p>
Some extensions can only be made to work with knowledge of the association
proxy&#8216;s internals. Extensions can access relevant state using
accessors on the association proxy:
</p>
<ul>
<li><tt>proxy_owner</tt> - Returns the object the association is part of.

</li>
<li><tt>proxy_reflection</tt> - Returns the reflection object that describes
the association.

</li>
<li><tt>proxy_target</tt> - Returns the associated object for <tt><a
href="ClassMethods.html#M001105">belongs_to</a></tt> and <tt><a
href="ClassMethods.html#M001104">has_one</a></tt>, or the collection of
associated objects for <tt><a
href="ClassMethods.html#M001103">has_many</a></tt> and <tt><a
href="ClassMethods.html#M001106">has_and_belongs_to_many</a></tt>.

</li>
</ul>
<h3>Association Join Models</h3>
<p>
Has Many associations can be configured with the <tt>:through</tt> option
to use an explicit join model to retrieve the data. This operates similarly
to a <tt><a
href="ClassMethods.html#M001106">has_and_belongs_to_many</a></tt>
association. The advantage is that you&#8216;re able to add validations,
callbacks, and extra attributes on the join model. Consider the following
schema:
</p>
<pre>
  class Author &lt; ActiveRecord::Base
    has_many :authorships
    has_many :books, :through =&gt; :authorships
  end

  class Authorship &lt; ActiveRecord::Base
    belongs_to :author
    belongs_to :book
  end

  @author = Author.find :first
  @author.authorships.collect { |a| a.book } # selects all books that the author's authorships belong to.
  @author.books                              # selects all books by using the Authorship join model
</pre>
<p>
You can also go through a <tt><a
href="ClassMethods.html#M001103">has_many</a></tt> association on the join
model:
</p>
<pre>
  class Firm &lt; ActiveRecord::Base
    has_many   :clients
    has_many   :invoices, :through =&gt; :clients
  end

  class Client &lt; ActiveRecord::Base
    belongs_to :firm
    has_many   :invoices
  end

  class Invoice &lt; ActiveRecord::Base
    belongs_to :client
  end

  @firm = Firm.find :first
  @firm.clients.collect { |c| c.invoices }.flatten # select all invoices for all clients of the firm
  @firm.invoices                                   # selects all invoices by going through the Client join model.
</pre>
<h3>Polymorphic Associations</h3>
<p>
Polymorphic associations on models are not restricted on what types of
models they can be associated with. Rather, they specify an interface that
a <tt><a href="ClassMethods.html#M001103">has_many</a></tt> association
must adhere to.
</p>
<pre>
  class Asset &lt; ActiveRecord::Base
    belongs_to :attachable, :polymorphic =&gt; true
  end

  class Post &lt; ActiveRecord::Base
    has_many :assets, :as =&gt; :attachable         # The :as option specifies the polymorphic interface to use.
  end

  @asset.attachable = @post
</pre>
<p>
This works by using a type column in addition to a foreign key to specify
the associated record. In the Asset example, you&#8216;d need an
<tt>attachable_id</tt> integer column and an <tt>attachable_type</tt>
string column.
</p>
<p>
Using polymorphic associations in combination with single table inheritance
(STI) is a little tricky. In order for the associations to work as
expected, ensure that you store the base model for the STI models in the
type column of the polymorphic association. To continue with the asset
example above, suppose there are guest posts and member posts that use the
posts table for STI. In this case, there must be a <tt>type</tt> column in
the posts table.
</p>
<pre>
  class Asset &lt; ActiveRecord::Base
    belongs_to :attachable, :polymorphic =&gt; true

    def attachable_type=(sType)
       super(sType.to_s.classify.constantize.base_class.to_s)
    end
  end

  class Post &lt; ActiveRecord::Base
    # because we store &quot;Post&quot; in attachable_type now :dependent =&gt; :destroy will work
    has_many :assets, :as =&gt; :attachable, :dependent =&gt; :destroy
  end

  class GuestPost &lt; Post
  end

  class MemberPost &lt; Post
  end
</pre>
<h2>Caching</h2>
<p>
All of the methods are built on a simple caching principle that will keep
the result of the last query around unless specifically instructed not to.
The cache is even shared across methods to make it even cheaper to use the
macro-added methods without worrying too much about performance at the
first go. Example:
</p>
<pre>
  project.milestones             # fetches milestones from the database
  project.milestones.size        # uses the milestone cache
  project.milestones.empty?      # uses the milestone cache
  project.milestones(true).size  # fetches milestones from the database
  project.milestones             # uses the milestone cache
</pre>
<h2>Eager loading of associations</h2>
<p>
Eager loading is a way to find objects of a certain class and a number of
named associations along with it in a single SQL call. This is one of the
easiest ways of to prevent the dreaded 1+N problem in which fetching 100
posts that each need to display their author triggers 101 database queries.
Through the use of eager loading, the 101 queries can be reduced to 1.
Example:
</p>
<pre>
  class Post &lt; ActiveRecord::Base
    belongs_to :author
    has_many   :comments
  end
</pre>
<p>
Consider the following loop using the class above:
</p>
<pre>
  for post in Post.find(:all)
    puts &quot;Post:            &quot; + post.title
    puts &quot;Written by:      &quot; + post.author.name
    puts &quot;Last comment on: &quot; + post.comments.first.created_on
  end
</pre>
<p>
To iterate over these one hundred posts, we&#8216;ll generate 201 database
queries. Let&#8216;s first just optimize it for retrieving the author:
</p>
<pre>
  for post in Post.find(:all, :include =&gt; :author)
</pre>
<p>
This references the name of the <tt><a
href="ClassMethods.html#M001105">belongs_to</a></tt> association that also
used the <tt>:author</tt> symbol, so the find will now weave in a join
something like this: <tt>LEFT OUTER JOIN authors ON authors.id =
posts.author_id</tt>. Doing so will cut down the number of queries from 201
to 101.
</p>
<p>
We can improve upon the situation further by referencing both associations
in the finder with:
</p>
<pre>
  for post in Post.find(:all, :include =&gt; [ :author, :comments ])
</pre>
<p>
That&#8216;ll add another join along the lines of: <tt>LEFT OUTER JOIN
comments ON comments.post_id = posts.id</tt>. And we&#8216;ll be down to 1
query.
</p>
<p>
To include a deep hierarchy of associations, use a hash:
</p>
<pre>
  for post in Post.find(:all, :include =&gt; [ :author, { :comments =&gt; { :author =&gt; :gravatar } } ])
</pre>
<p>
That&#8216;ll grab not only all the comments but all their authors and
gravatar pictures. You can mix and match symbols, arrays and hashes in any
combination to describe the associations you want to load.
</p>
<p>
All of this power shouldn&#8216;t fool you into thinking that you can pull
out huge amounts of data with no performance penalty just because
you&#8216;ve reduced the number of queries. The database still needs to
send all the data to Active Record and it still needs to be processed. So
it&#8216;s no catch-all for performance problems, but it&#8216;s a great
way to cut down on the number of queries in a situation as the one
described above.
</p>
<p>
Since the eager loading pulls from multiple tables, you&#8216;ll have to
disambiguate any column references in both conditions and orders. So
<tt>:order =&gt; &quot;posts.id DESC&quot;</tt> will work while <tt>:order
=&gt; &quot;id DESC&quot;</tt> will not. Because eager loading generates
the <tt>SELECT</tt> statement too, the <tt>:select</tt> option is ignored.
</p>
<p>
You can use eager loading on multiple associations from the same table, but
you cannot use those associations in orders and conditions as there is
currently not any way to disambiguate them. Eager loading will not pull
additional attributes on join tables, so &quot;rich associations&quot; with
<tt><a href="ClassMethods.html#M001106">has_and_belongs_to_many</a></tt>
are not a good fit for eager loading.
</p>
<p>
When eager loaded, conditions are interpolated in the context of the model
class, not the model instance. Conditions are lazily interpolated before
the actual model exists.
</p>
<h2>Table Aliasing</h2>
<p>
ActiveRecord uses table aliasing in the case that a table is referenced
multiple times in a join. If a table is referenced only once, the standard
table name is used. The second time, the table is aliased as
<tt>#{reflection_name}_#{parent_table_name}</tt>. Indexes are appended for
any more successive uses of the table name.
</p>
<pre>
  Post.find :all, :include =&gt; :comments
  # =&gt; SELECT ... FROM posts LEFT OUTER JOIN comments ON ...
  Post.find :all, :include =&gt; :special_comments # STI
  # =&gt; SELECT ... FROM posts LEFT OUTER JOIN comments ON ... AND comments.type = 'SpecialComment'
  Post.find :all, :include =&gt; [:comments, :special_comments] # special_comments is the reflection name, posts is the parent table name
  # =&gt; SELECT ... FROM posts LEFT OUTER JOIN comments ON ... LEFT OUTER JOIN comments special_comments_posts
</pre>
<p>
Acts as tree example:
</p>
<pre>
  TreeMixin.find :all, :include =&gt; :children
  # =&gt; SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ...
  TreeMixin.find :all, :include =&gt; {:children =&gt; :parent} # using cascading eager includes
  # =&gt; SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ...
                              LEFT OUTER JOIN parents_mixins ...
  TreeMixin.find :all, :include =&gt; {:children =&gt; {:parent =&gt; :children}}
  # =&gt; SELECT ... FROM mixins LEFT OUTER JOIN mixins childrens_mixins ...
                              LEFT OUTER JOIN parents_mixins ...
                              LEFT OUTER JOIN mixins childrens_mixins_2
</pre>
<p>
Has and Belongs to Many join tables use the same idea, but add a
<tt>_join</tt> suffix:
</p>
<pre>
  Post.find :all, :include =&gt; :categories
  # =&gt; SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ...
  Post.find :all, :include =&gt; {:categories =&gt; :posts}
  # =&gt; SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ...
                             LEFT OUTER JOIN categories_posts posts_categories_join LEFT OUTER JOIN posts posts_categories
  Post.find :all, :include =&gt; {:categories =&gt; {:posts =&gt; :categories}}
  # =&gt; SELECT ... FROM posts LEFT OUTER JOIN categories_posts ... LEFT OUTER JOIN categories ...
                             LEFT OUTER JOIN categories_posts posts_categories_join LEFT OUTER JOIN posts posts_categories
                             LEFT OUTER JOIN categories_posts categories_posts_join LEFT OUTER JOIN categories categories_posts
</pre>
<p>
If you wish to specify your own custom joins using a <tt>:joins</tt>
option, those table names will take precedence over the eager associations:
</p>
<pre>
  Post.find :all, :include =&gt; :comments, :joins =&gt; &quot;inner join comments ...&quot;
  # =&gt; SELECT ... FROM posts LEFT OUTER JOIN comments_posts ON ... INNER JOIN comments ...
  Post.find :all, :include =&gt; [:comments, :special_comments], :joins =&gt; &quot;inner join comments ...&quot;
  # =&gt; SELECT ... FROM posts LEFT OUTER JOIN comments comments_posts ON ...
                             LEFT OUTER JOIN comments special_comments_posts ...
                             INNER JOIN comments ...
</pre>
<p>
Table aliases are automatically truncated according to the maximum length
of table identifiers according to the specific database.
</p>
<h2>Modules</h2>
<p>
By default, associations will look for objects within the current module
scope. Consider:
</p>
<pre>
  module MyApplication
    module Business
      class Firm &lt; ActiveRecord::Base
         has_many :clients
       end

      class Company &lt; ActiveRecord::Base; end
    end
  end
</pre>
<p>
When <tt>Firm#clients</tt> is called, it will in turn call
<tt>MyApplication::Business::Company.find(firm.id)</tt>. If you want to
associate with a class in another module scope, this can be done by
specifying the complete class name. Example:
</p>
<pre>
  module MyApplication
    module Business
      class Firm &lt; ActiveRecord::Base; end
    end

    module Billing
      class Account &lt; ActiveRecord::Base
        belongs_to :firm, :class_name =&gt; &quot;MyApplication::Business::Firm&quot;
      end
    end
  end
</pre>
<h2>Type safety with <tt><a href="../AssociationTypeMismatch.html">ActiveRecord::AssociationTypeMismatch</a></tt></h2>
<p>
If you attempt to assign an object to an association that doesn&#8216;t
match the inferred or specified <tt>:class_name</tt>, you&#8216;ll get an
<tt><a
href="../AssociationTypeMismatch.html">ActiveRecord::AssociationTypeMismatch</a></tt>.
</p>
<h2>Options</h2>
<p>
All of the association macros can be specialized through options. This
makes cases more complex than the simple and guessable ones possible.
</p>

    </div>


   </div>

    <div id="method-list">
      <h3 class="section-bar">Methods</h3>

      <div class="name-list">
      <a href="#M001105">belongs_to</a>&nbsp;&nbsp;
      <a href="#M001106">has_and_belongs_to_many</a>&nbsp;&nbsp;
      <a href="#M001103">has_many</a>&nbsp;&nbsp;
      <a href="#M001104">has_one</a>&nbsp;&nbsp;
      </div>
    </div>

  </div>


    <!-- if includes -->

    <div id="section">





      


    <!-- if method_list -->
    <div id="methods">
      <h3 class="section-bar">Public Instance methods</h3>

      <div id="method-M001105" class="method-detail">
        <a name="M001105"></a>

        <div class="method-heading">
          <a href="#M001105" class="method-signature">
          <span class="method-name">belongs_to</span><span class="method-args">(association_id, options = {})</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Adds the following methods for retrieval and query for a single associated
object for which this object holds an id: <tt>association</tt> is replaced
with the symbol passed as the first argument, so <tt><a
href="ClassMethods.html#M001105">belongs_to</a> :author</tt> would add
among others <tt>author.nil?</tt>.
</p>
<ul>
<li><tt>association(force_reload = false)</tt> - returns the associated object.
<tt>nil</tt> is returned if none is found.

</li>
<li><tt>association=(associate)</tt> - assigns the associate object, extracts
the primary key, and sets it as the foreign key.

</li>
<li><tt>association.nil?</tt> - returns <tt>true</tt> if there is no associated
object.

</li>
<li><tt>build_association(attributes = {})</tt> - returns a new object of the
associated type that has been instantiated with <tt>attributes</tt> and
linked to this object through a foreign key, but has not yet been saved.

</li>
<li><tt>create_association(attributes = {})</tt> - returns a new object of the
associated type that has been instantiated with <tt>attributes</tt>, linked
to this object through a foreign key, and that has already been saved (if
it passed the validation).

</li>
</ul>
<p>
Example: A Post class declares <tt><a
href="ClassMethods.html#M001105">belongs_to</a> :author</tt>, which will
add:
</p>
<ul>
<li><tt>Post#author</tt> (similar to <tt>Author.find(author_id)</tt>)

</li>
<li><tt>Post#author=(author)</tt> (similar to <tt>post.author_id =
author.id</tt>)

</li>
<li><tt>Post#author?</tt> (similar to <tt>post.author == some_author</tt>)

</li>
<li><tt>Post#author.nil?</tt>

</li>
<li><tt>Post#build_author</tt> (similar to <tt>post.author = Author.new</tt>)

</li>
<li><tt>Post#create_author</tt> (similar to <tt>post.author = Author.new;
post.author.save; post.author</tt>)

</li>
</ul>
<p>
The declaration can also include an options hash to specialize the behavior
of the association.
</p>
<p>
Options are:
</p>
<ul>
<li><tt>:class_name</tt> - specify the class name of the association. Use it
only if that name can&#8216;t be inferred from the association name. So
<tt><a href="ClassMethods.html#M001104">has_one</a> :author</tt> will by
default be linked to the <tt>Author</tt> class, but if the real class name
is <tt>Person</tt>, you&#8216;ll have to specify it with this option.

</li>
<li><tt>:conditions</tt> - specify the conditions that the associated object
must meet in order to be included as a <tt>WHERE</tt> SQL fragment, such as
<tt>authorized = 1</tt>.

</li>
<li><tt>:order</tt> - specify the order in which the associated objects are
returned as an <tt>ORDER BY</tt> SQL fragment, such as <tt>last_name,
first_name DESC</tt>

</li>
<li><tt>:foreign_key</tt> - specify the foreign key used for the association.
By default this is guessed to be the name of the associated class in
lower-case and <tt>_id</tt> suffixed. So a <tt>Person</tt> class that makes
a <tt><a href="ClassMethods.html#M001105">belongs_to</a></tt> association
to a <tt>Boss</tt> class will use <tt>boss_id</tt> as the default
<tt>foreign_key</tt>.

</li>
<li><tt>:counter_cache</tt> - caches the number of belonging objects on the
associate class through the use of <tt>increment_counter</tt> and
<tt>decrement_counter</tt>. The counter cache is incremented when an object
of this class is created and decremented when it&#8216;s destroyed. This
requires that a column named <tt>#{table_name}_count</tt> (such as
<tt>comments_count</tt> for a belonging <tt>Comment</tt> class) is used on
the associate class (such as a <tt>Post</tt> class). You can also specify a
custom counter cache column by providing a column name instead of a
<tt>true</tt>/<tt>false</tt> value to this option (e.g., <tt>:counter_cache
=&gt; :my_custom_counter</tt>.) Note: Specifying a counter_cache will add
it to that model&#8216;s list of readonly attributes using attr_readonly.

</li>
<li><tt>:include</tt> - specify second-order associations that should be eager
loaded when this object is loaded.

</li>
<li><tt>:polymorphic</tt> - specify this association is a polymorphic
association by passing <tt>true</tt>. Note: If you&#8216;ve enabled the
counter cache, then you may want to add the counter cache attribute to the
attr_readonly list in the associated classes (e.g. class Post;
attr_readonly :comments_count; end).

</li>
</ul>
<p>
Option examples:
</p>
<pre>
  belongs_to :firm, :foreign_key =&gt; &quot;client_of&quot;
  belongs_to :author, :class_name =&gt; &quot;Person&quot;, :foreign_key =&gt; &quot;author_id&quot;
  belongs_to :valid_coupon, :class_name =&gt; &quot;Coupon&quot;, :foreign_key =&gt; &quot;coupon_id&quot;,
             :conditions =&gt; 'discounts &gt; #{payments_count}'
  belongs_to :attachable, :polymorphic =&gt; true
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001105-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001105-source">
<pre>
     <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/associations.rb, line 795</span>
795:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">belongs_to</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span> = {})
796:         <span class="ruby-identifier">reflection</span> = <span class="ruby-identifier">create_belongs_to_reflection</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span>)
797:         
798:         <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">options</span>[<span class="ruby-identifier">:polymorphic</span>]
799:           <span class="ruby-identifier">association_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">BelongsToPolymorphicAssociation</span>)
800: 
801:           <span class="ruby-identifier">module_eval</span> <span class="ruby-keyword kw">do</span>
802:             <span class="ruby-identifier">before_save</span> <span class="ruby-value str">&quot;association = instance_variable_get(\&quot;@\#{reflection.name}\&quot;)\nif association &amp;&amp; association.target\nif association.new_record?\nassociation.save(true)\nend\n\nif association.updated?\nself[\&quot;\#{reflection.primary_key_name}\&quot;] = association.id\nself[\&quot;\#{reflection.options[:foreign_type]}\&quot;] = association.class.base_class.name.to_s\nend\nend\n&quot;</span>
803:           <span class="ruby-keyword kw">end</span>
804:         <span class="ruby-keyword kw">else</span>
805:           <span class="ruby-identifier">association_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">BelongsToAssociation</span>)
806:           <span class="ruby-identifier">association_constructor_method</span>(<span class="ruby-identifier">:build</span>,  <span class="ruby-identifier">reflection</span>, <span class="ruby-constant">BelongsToAssociation</span>)
807:           <span class="ruby-identifier">association_constructor_method</span>(<span class="ruby-identifier">:create</span>, <span class="ruby-identifier">reflection</span>, <span class="ruby-constant">BelongsToAssociation</span>)
808: 
809:           <span class="ruby-identifier">module_eval</span> <span class="ruby-keyword kw">do</span>
810:             <span class="ruby-identifier">before_save</span> <span class="ruby-value str">&quot;association = instance_variable_get(\&quot;@\#{reflection.name}\&quot;)\nif !association.nil?\nif association.new_record?\nassociation.save(true)\nend\n\nif association.updated?\nself[\&quot;\#{reflection.primary_key_name}\&quot;] = association.id\nend\nend\n&quot;</span>
811:           <span class="ruby-keyword kw">end</span>
812:         <span class="ruby-keyword kw">end</span>
813: 
814:         <span class="ruby-comment cmt"># Create the callbacks to update counter cache</span>
815:         <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:counter_cache</span>]
816:           <span class="ruby-identifier">cache_column</span> = <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:counter_cache</span>] <span class="ruby-operator">==</span> <span class="ruby-keyword kw">true</span> <span class="ruby-operator">?</span>
817:             <span class="ruby-node">&quot;#{self.to_s.underscore.pluralize}_count&quot;</span> <span class="ruby-operator">:</span>
818:             <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:counter_cache</span>]
819: 
820:           <span class="ruby-identifier">module_eval</span>(
821:             <span class="ruby-node">&quot;after_create '#{reflection.name}.class.increment_counter(\&quot;#{cache_column}\&quot;, #{reflection.primary_key_name})&quot;</span> <span class="ruby-operator">+</span>
822:             <span class="ruby-node">&quot; unless #{reflection.name}.nil?'&quot;</span>
823:           )
824: 
825:           <span class="ruby-identifier">module_eval</span>(
826:             <span class="ruby-node">&quot;before_destroy '#{reflection.name}.class.decrement_counter(\&quot;#{cache_column}\&quot;, #{reflection.primary_key_name})&quot;</span> <span class="ruby-operator">+</span>
827:             <span class="ruby-node">&quot; unless #{reflection.name}.nil?'&quot;</span>
828:           )
829:           
830:           <span class="ruby-identifier">module_eval</span>(
831:             <span class="ruby-node">&quot;#{reflection.class_name}.send(:attr_readonly,\&quot;#{cache_column}\&quot;.intern) if defined?(#{reflection.class_name}) &amp;&amp; #{reflection.class_name}.respond_to?(:attr_readonly)&quot;</span>
832:           )
833:         <span class="ruby-keyword kw">end</span>
834:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001106" class="method-detail">
        <a name="M001106"></a>

        <div class="method-heading">
          <a href="#M001106" class="method-signature">
          <span class="method-name">has_and_belongs_to_many</span><span class="method-args">(association_id, options = {}, &amp;extension)</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Associates two classes via an intermediate join table. Unless the join
table is explicitly specified as an option, it is guessed using the lexical
order of the class names. So a join between <tt>Developer</tt> and
<tt>Project</tt> will give the default join table name of
<tt>developers_projects</tt> because &quot;D&quot; outranks &quot;P&quot;.
Note that this precedence is calculated using the <tt>&lt;</tt> operator
for <tt>String</tt>. This means that if the strings are of different
lengths, and the strings are equal when compared up to the shortest length,
then the longer string is considered of higher lexical precedence than the
shorter one. For example, one would expect the tables <tt>paper_boxes</tt>
and <tt>papers</tt> to generate a join table name of
<tt>papers_paper_boxes</tt> because of the length of the name
<tt>paper_boxes</tt>, but it in fact generates a join table name of
<tt>paper_boxes_papers</tt>. Be aware of this caveat, and use the custom
<tt>join_table</tt> option if you need to.
</p>
<p>
Deprecated: Any additional fields added to the join table will be placed as
attributes when pulling records out through <tt><a
href="ClassMethods.html#M001106">has_and_belongs_to_many</a></tt>
associations. Records returned from join tables with additional attributes
will be marked as <tt>ReadOnly</tt> (because we can&#8216;t save changes to
the additional attributes). It&#8216;s strongly recommended that you
upgrade any associations with attributes to a real join model (see
introduction).
</p>
<p>
Adds the following methods for retrieval and query: <tt>collection</tt> is
replaced with the symbol passed as the first argument, so <tt><a
href="ClassMethods.html#M001106">has_and_belongs_to_many</a>
:categories</tt> would add among others <tt>categories.empty?</tt>.
</p>
<ul>
<li><tt>collection(force_reload = false)</tt> - returns an array of all the
associated objects. An empty array is returned if none are found.

</li>
<li><tt>collection&lt;&lt;(object, &#8230;)</tt> - adds one or more objects to
the collection by creating associations in the join table
(<tt>collection.push</tt> and <tt>collection.concat</tt> are aliases to
this method).

</li>
<li><tt>collection.delete(object, &#8230;)</tt> - removes one or more objects
from the collection by removing their associations from the join table.
This does not destroy the objects.

</li>
<li><tt>collection=objects</tt> - replaces the collection&#8216;s content by
deleting and adding objects as appropriate.

</li>
<li><tt>collection_singular_ids</tt> - returns an array of the associated
objects&#8217; ids

</li>
<li><tt>collection_singular_ids=ids</tt> - replace the collection by the
objects identified by the primary keys in <tt>ids</tt>

</li>
<li><tt>collection.clear</tt> - removes every object from the collection. This
does not destroy the objects.

</li>
<li><tt>collection.empty?</tt> - returns <tt>true</tt> if there are no
associated objects.

</li>
<li><tt>collection.size</tt> - returns the number of associated objects.

</li>
<li><tt>collection.find(id)</tt> - finds an associated object responding to the
<tt>id</tt> and that meets the condition that it has to be associated with
this object.

</li>
<li><tt>collection.build(attributes = {})</tt> - returns a new object of the
collection type that has been instantiated with <tt>attributes</tt> and
linked to this object through the join table, but has not yet been saved.

</li>
<li><tt>collection.create(attributes = {})</tt> - returns a new object of the
collection type that has been instantiated with <tt>attributes</tt>, linked
to this object through the join table, and that has already been saved (if
it passed the validation).

</li>
</ul>
<p>
Example: A Developer class declares <tt><a
href="ClassMethods.html#M001106">has_and_belongs_to_many</a>
:projects</tt>, which will add:
</p>
<ul>
<li><tt>Developer#projects</tt>

</li>
<li><tt>Developer#projects&lt;&lt;</tt>

</li>
<li><tt>Developer#projects.delete</tt>

</li>
<li><tt>Developer#projects=</tt>

</li>
<li><tt>Developer#project_ids</tt>

</li>
<li><tt>Developer#project_ids=</tt>

</li>
<li><tt>Developer#projects.clear</tt>

</li>
<li><tt>Developer#projects.empty?</tt>

</li>
<li><tt>Developer#projects.size</tt>

</li>
<li><tt>Developer#projects.find(id)</tt>

</li>
<li><tt>Developer#projects.build</tt> (similar to
<tt>Project.new(&quot;project_id&quot; =&gt; id)</tt>)

</li>
<li><tt>Developer#projects.create</tt> (similar to <tt>c =
Project.new(&quot;project_id&quot; =&gt; id); c.save; c</tt>)

</li>
</ul>
<p>
The declaration may include an options hash to specialize the behavior of
the association.
</p>
<p>
Options are:
</p>
<ul>
<li><tt>:class_name</tt> - specify the class name of the association. Use it
only if that name can&#8216;t be inferred from the association name. So
<tt><a href="ClassMethods.html#M001106">has_and_belongs_to_many</a>
:projects</tt> will by default be linked to the <tt>Project</tt> class, but
if the real class name is <tt>SuperProject</tt>, you&#8216;ll have to
specify it with this option.

</li>
<li><tt>:join_table</tt> - specify the name of the join table if the default
based on lexical order isn&#8216;t what you want. WARNING: If you&#8216;re
overwriting the table name of either class, the <tt>table_name</tt> method
MUST be declared underneath any <tt><a
href="ClassMethods.html#M001106">has_and_belongs_to_many</a></tt>
declaration in order to work.

</li>
<li><tt>:foreign_key</tt> - specify the foreign key used for the association.
By default this is guessed to be the name of this class in lower-case and
<tt>_id</tt> suffixed. So a <tt>Person</tt> class that makes a <tt><a
href="ClassMethods.html#M001106">has_and_belongs_to_many</a></tt>
association will use <tt>person_id</tt> as the default
<tt>foreign_key</tt>.

</li>
<li><tt>:association_foreign_key</tt> - specify the association foreign key
used for the association. By default this is guessed to be the name of the
associated class in lower-case and <tt>_id</tt> suffixed. So if the
associated class is <tt>Project</tt>, the <tt><a
href="ClassMethods.html#M001106">has_and_belongs_to_many</a></tt>
association will use <tt>project_id</tt> as the default association
<tt>foreign_key</tt>.

</li>
<li><tt>:conditions</tt> - specify the conditions that the associated object
must meet in order to be included as a <tt>WHERE</tt> SQL fragment, such as
<tt>authorized = 1</tt>.

</li>
<li><tt>:order</tt> - specify the order in which the associated objects are
returned as an <tt>ORDER BY</tt> SQL fragment, such as <tt>last_name,
first_name DESC</tt>

</li>
<li><tt>:uniq</tt> - if set to <tt>true</tt>, duplicate associated objects will
be ignored by accessors and query methods

</li>
<li><tt>:finder_sql</tt> - overwrite the default generated SQL statement used
to fetch the association with a manual statement

</li>
<li><tt>:delete_sql</tt> - overwrite the default generated SQL statement used
to remove links between the associated classes with a manual statement

</li>
<li><tt>:insert_sql</tt> - overwrite the default generated SQL statement used
to add links between the associated classes with a manual statement

</li>
<li><tt>:extend</tt> - anonymous module for extending the proxy, see
&quot;Association extensions&quot;.

</li>
<li><tt>:include</tt> - specify second-order associations that should be eager
loaded when the collection is loaded.

</li>
<li><tt>:group</tt>: An attribute name by which the result should be grouped.
Uses the <tt>GROUP BY</tt> SQL-clause.

</li>
<li><tt>:limit</tt>: An integer determining the limit on the number of rows
that should be returned.

</li>
<li><tt>:offset</tt>: An integer determining the offset from where the rows
should be fetched. So at 5, it would skip the first 4 rows.

</li>
<li><tt>:select</tt>: By default, this is <tt>*</tt> as in <tt>SELECT *
FROM</tt>, but can be changed if, for example, you want to do a join but
not include the joined columns.

</li>
</ul>
<p>
Option examples:
</p>
<pre>
  has_and_belongs_to_many :projects
  has_and_belongs_to_many :projects, :include =&gt; [ :milestones, :manager ]
  has_and_belongs_to_many :nations, :class_name =&gt; &quot;Country&quot;
  has_and_belongs_to_many :categories, :join_table =&gt; &quot;prods_cats&quot;
  has_and_belongs_to_many :active_projects, :join_table =&gt; 'developers_projects', :delete_sql =&gt;
  'DELETE FROM developers_projects WHERE active=1 AND developer_id = #{id} AND project_id = #{record.id}'
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001106-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001106-source">
<pre>
     <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/associations.rb, line 951</span>
951:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">has_and_belongs_to_many</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span> = {}, <span class="ruby-operator">&amp;</span><span class="ruby-identifier">extension</span>)
952:         <span class="ruby-identifier">reflection</span> = <span class="ruby-identifier">create_has_and_belongs_to_many_reflection</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span>, <span class="ruby-operator">&amp;</span><span class="ruby-identifier">extension</span>)
953:         
954:         <span class="ruby-identifier">add_multiple_associated_save_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>)
955:         <span class="ruby-identifier">collection_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasAndBelongsToManyAssociation</span>)
956: 
957:         <span class="ruby-comment cmt"># Don't use a before_destroy callback since users' before_destroy</span>
958:         <span class="ruby-comment cmt"># callbacks will be executed after the association is wiped out.</span>
959:         <span class="ruby-identifier">old_method</span> = <span class="ruby-node">&quot;destroy_without_habtm_shim_for_#{reflection.name}&quot;</span>
960:         <span class="ruby-identifier">class_eval</span> <span class="ruby-value str">&quot;alias_method :\#{old_method}, :destroy_without_callbacks\ndef destroy_without_callbacks\n\#{reflection.name}.clear\n\#{old_method}\nend\n&quot;</span> <span class="ruby-keyword kw">unless</span> <span class="ruby-identifier">method_defined?</span>(<span class="ruby-identifier">old_method</span>)
961: 
962:         <span class="ruby-identifier">add_association_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>, <span class="ruby-identifier">options</span>)
963:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001103" class="method-detail">
        <a name="M001103"></a>

        <div class="method-heading">
          <a href="#M001103" class="method-signature">
          <span class="method-name">has_many</span><span class="method-args">(association_id, options = {}, &amp;extension)</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Adds the following methods for retrieval and query of collections of
associated objects: <tt>collection</tt> is replaced with the symbol passed
as the first argument, so <tt><a
href="ClassMethods.html#M001103">has_many</a> :clients</tt> would add among
others <tt>clients.empty?</tt>.
</p>
<ul>
<li><tt>collection(force_reload = false)</tt> - returns an array of all the
associated objects. An empty array is returned if none are found.

</li>
<li><tt>collection&lt;&lt;(object, &#8230;)</tt> - adds one or more objects to
the collection by setting their foreign keys to the collection&#8216;s
primary key.

</li>
<li><tt>collection.delete(object, &#8230;)</tt> - removes one or more objects
from the collection by setting their foreign keys to NULL. This will also
destroy the objects if they&#8216;re declared as <tt><a
href="ClassMethods.html#M001105">belongs_to</a></tt> and dependent on this
model.

</li>
<li><tt>collection=objects</tt> - replaces the collections content by deleting
and adding objects as appropriate.

</li>
<li><tt>collection_singular_ids</tt> - returns an array of the associated
objects&#8217; ids

</li>
<li><tt>collection_singular_ids=ids</tt> - replace the collection with the
objects identified by the primary keys in <tt>ids</tt>

</li>
<li><tt>collection.clear</tt> - removes every object from the collection. This
destroys the associated objects if they are associated with <tt>:dependent
=&gt; :destroy</tt>, deletes them directly from the database if
<tt>:dependent =&gt; :delete_all</tt>, otherwise sets their foreign keys to
NULL.

</li>
<li><tt>collection.empty?</tt> - returns <tt>true</tt> if there are no
associated objects.

</li>
<li><tt>collection.size</tt> - returns the number of associated objects.

</li>
<li><tt>collection.find</tt> - finds an associated object according to the same
rules as <a href="../Base.html#M001376">Base.find</a>.

</li>
<li><tt>collection.build(attributes = {}, &#8230;)</tt> - returns one or more
new objects of the collection type that have been instantiated with
<tt>attributes</tt> and linked to this object through a foreign key, but
have not yet been saved. *Note:* This only works if an associated object
already exists, not if it&#8216;s <tt>nil</tt>!

</li>
<li><tt>collection.create(attributes = {})</tt> - returns a new object of the
collection type that has been instantiated with <tt>attributes</tt>, linked
to this object through a foreign key, and that has already been saved (if
it passed the validation). *Note:* This only works if an associated object
already exists, not if it&#8216;s <tt>nil</tt>!

</li>
</ul>
<p>
Example: A <tt>Firm</tt> class declares <tt><a
href="ClassMethods.html#M001103">has_many</a> :clients</tt>, which will
add:
</p>
<ul>
<li><tt>Firm#clients</tt> (similar to <tt>Clients.find :all, :conditions =&gt;
&quot;firm_id = #{id}&quot;</tt>)

</li>
<li><tt>Firm#clients&lt;&lt;</tt>

</li>
<li><tt>Firm#clients.delete</tt>

</li>
<li><tt>Firm#clients=</tt>

</li>
<li><tt>Firm#client_ids</tt>

</li>
<li><tt>Firm#client_ids=</tt>

</li>
<li><tt>Firm#clients.clear</tt>

</li>
<li><tt>Firm#clients.empty?</tt> (similar to <tt>firm.clients.size == 0</tt>)

</li>
<li><tt>Firm#clients.size</tt> (similar to <tt>Client.count &quot;firm_id =
#{id}&quot;</tt>)

</li>
<li><tt>Firm#clients.find</tt> (similar to <tt>Client.find(id, :conditions
=&gt; &quot;firm_id = #{id}&quot;)</tt>)

</li>
<li><tt>Firm#clients.build</tt> (similar to <tt>Client.new(&quot;firm_id&quot;
=&gt; id)</tt>)

</li>
<li><tt>Firm#clients.create</tt> (similar to <tt>c =
Client.new(&quot;firm_id&quot; =&gt; id); c.save; c</tt>)

</li>
</ul>
<p>
The declaration can also include an options hash to specialize the behavior
of the association.
</p>
<p>
Options are:
</p>
<ul>
<li><tt>:class_name</tt> - specify the class name of the association. Use it
only if that name can&#8216;t be inferred from the association name. So
<tt><a href="ClassMethods.html#M001103">has_many</a> :products</tt> will by
default be linked to the <tt>Product</tt> class, but if the real class name
is <tt>SpecialProduct</tt>, you&#8216;ll have to specify it with this
option.

</li>
<li><tt>:conditions</tt> - specify the conditions that the associated objects
must meet in order to be included as a <tt>WHERE</tt> SQL fragment, such as
<tt>price &gt; 5 AND name LIKE &#8216;B%&#8217;</tt>.

</li>
<li><tt>:order</tt> - specify the order in which the associated objects are
returned as an <tt>ORDER BY</tt> SQL fragment, such as <tt>last_name,
first_name DESC</tt>

</li>
<li><tt>:foreign_key</tt> - specify the foreign key used for the association.
By default this is guessed to be the name of this class in lower-case and
<tt>_id</tt> suffixed. So a <tt>Person</tt> class that makes a <tt><a
href="ClassMethods.html#M001103">has_many</a></tt> association will use
<tt>person_id</tt> as the default <tt>foreign_key</tt>.

</li>
<li><tt>:dependent</tt> - if set to <tt>:destroy</tt> all the associated
objects are destroyed alongside this object by calling their destroy
method. If set to <tt>:delete_all</tt> all associated objects are deleted
<b>without</b> calling their destroy method. If set to <tt>:nullify</tt>
all associated objects&#8217; foreign keys are set to <tt>NULL</tt>
<b>without</b> calling their save callbacks.

</li>
<li><tt>:finder_sql</tt> - specify a complete SQL statement to fetch the
association. This is a good way to go for complex associations that depend
on multiple tables. Note: When this option is used,
<tt>find_in_collection</tt> is <em>not</em> added.

</li>
<li><tt>:counter_sql</tt> - specify a complete SQL statement to fetch the size
of the association. If <tt>:finder_sql</tt> is specified but not
<tt>:counter_sql</tt>, <tt>:counter_sql</tt> will be generated by replacing
<tt>SELECT &#8230; FROM</tt> with <tt>SELECT COUNT(*) FROM</tt>.

</li>
<li><tt>:extend</tt> - specify a named module for extending the proxy. See
&quot;Association extensions&quot;.

</li>
<li><tt>:include</tt> - specify second-order associations that should be eager
loaded when the collection is loaded.

</li>
<li><tt>:group</tt>: An attribute name by which the result should be grouped.
Uses the <tt>GROUP BY</tt> SQL-clause.

</li>
<li><tt>:limit</tt>: An integer determining the limit on the number of rows
that should be returned.

</li>
<li><tt>:offset</tt>: An integer determining the offset from where the rows
should be fetched. So at 5, it would skip the first 4 rows.

</li>
<li><tt>:select</tt>: By default, this is <tt>*</tt> as in <tt>SELECT *
FROM</tt>, but can be changed if you, for example, want to do a join but
not include the joined columns.

</li>
<li><tt>:as</tt>: Specifies a polymorphic interface (See <tt><a
href="ClassMethods.html#M001105">belongs_to</a></tt>).

</li>
<li><tt>:through</tt>: Specifies a Join Model through which to perform the
query. Options for <tt>:class_name</tt> and <tt>:foreign_key</tt> are
ignored, as the association uses the source reflection. You can only use a
<tt>:through</tt> query through a <tt><a
href="ClassMethods.html#M001105">belongs_to</a></tt> or <tt><a
href="ClassMethods.html#M001103">has_many</a></tt> association on the join
model.

</li>
<li><tt>:source</tt>: Specifies the source association name used by <tt><a
href="ClassMethods.html#M001103">has_many</a> :through</tt> queries. Only
use it if the name cannot be inferred from the association. <tt><a
href="ClassMethods.html#M001103">has_many</a> :subscribers, :through =&gt;
:subscriptions</tt> will look for either <tt>:subscribers</tt> or
<tt>:subscriber</tt> on <tt>Subscription</tt>, unless a <tt>:source</tt> is
given.

</li>
<li><tt>:source_type</tt>: Specifies type of the source association used by
<tt><a href="ClassMethods.html#M001103">has_many</a> :through</tt> queries
where the source association is a polymorphic <tt><a
href="ClassMethods.html#M001105">belongs_to</a></tt>.

</li>
<li><tt>:uniq</tt> - if set to <tt>true</tt>, duplicates will be omitted from
the collection. Useful in conjunction with <tt>:through</tt>.

</li>
</ul>
<p>
Option examples:
</p>
<pre>
  has_many :comments, :order =&gt; &quot;posted_on&quot;
  has_many :comments, :include =&gt; :author
  has_many :people, :class_name =&gt; &quot;Person&quot;, :conditions =&gt; &quot;deleted = 0&quot;, :order =&gt; &quot;name&quot;
  has_many :tracks, :order =&gt; &quot;position&quot;, :dependent =&gt; :destroy
  has_many :comments, :dependent =&gt; :nullify
  has_many :tags, :as =&gt; :taggable
  has_many :subscribers, :through =&gt; :subscriptions, :source =&gt; :user
  has_many :subscribers, :class_name =&gt; &quot;Person&quot;, :finder_sql =&gt;
      'SELECT DISTINCT people.* ' +
      'FROM people p, post_subscriptions ps ' +
      'WHERE ps.post_id = #{id} AND ps.person_id = p.id ' +
      'ORDER BY p.first_name'
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001103-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001103-source">
<pre>
     <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/associations.rb, line 666</span>
666:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">has_many</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span> = {}, <span class="ruby-operator">&amp;</span><span class="ruby-identifier">extension</span>)
667:         <span class="ruby-identifier">reflection</span> = <span class="ruby-identifier">create_has_many_reflection</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span>, <span class="ruby-operator">&amp;</span><span class="ruby-identifier">extension</span>)
668: 
669:         <span class="ruby-identifier">configure_dependency_for_has_many</span>(<span class="ruby-identifier">reflection</span>)
670: 
671:         <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">options</span>[<span class="ruby-identifier">:through</span>]
672:           <span class="ruby-identifier">collection_reader_method</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasManyThroughAssociation</span>)
673:           <span class="ruby-identifier">collection_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasManyThroughAssociation</span>, <span class="ruby-keyword kw">false</span>)
674:         <span class="ruby-keyword kw">else</span>
675:           <span class="ruby-identifier">add_multiple_associated_save_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>)
676:           <span class="ruby-identifier">add_association_callbacks</span>(<span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">name</span>, <span class="ruby-identifier">reflection</span>.<span class="ruby-identifier">options</span>)
677:           <span class="ruby-identifier">collection_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasManyAssociation</span>)
678:         <span class="ruby-keyword kw">end</span>
679:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>

      <div id="method-M001104" class="method-detail">
        <a name="M001104"></a>

        <div class="method-heading">
          <a href="#M001104" class="method-signature">
          <span class="method-name">has_one</span><span class="method-args">(association_id, options = {})</span>
          </a>
        </div>
      
        <div class="method-description">
          <p>
Adds the following methods for retrieval and query of a single associated
object: <tt>association</tt> is replaced with the symbol passed as the
first argument, so <tt><a href="ClassMethods.html#M001104">has_one</a>
:manager</tt> would add among others <tt>manager.nil?</tt>.
</p>
<ul>
<li><tt>association(force_reload = false)</tt> - returns the associated object.
<tt>nil</tt> is returned if none is found.

</li>
<li><tt>association=(associate)</tt> - assigns the associate object, extracts
the primary key, sets it as the foreign key, and saves the associate
object.

</li>
<li><tt>association.nil?</tt> - returns <tt>true</tt> if there is no associated
object.

</li>
<li><tt>build_association(attributes = {})</tt> - returns a new object of the
associated type that has been instantiated with <tt>attributes</tt> and
linked to this object through a foreign key, but has not yet been saved.
Note: This ONLY works if an association already exists. It will NOT work if
the association is <tt>nil</tt>.

</li>
<li><tt>create_association(attributes = {})</tt> - returns a new object of the
associated type that has been instantiated with <tt>attributes</tt>, linked
to this object through a foreign key, and that has already been saved (if
it passed the validation).

</li>
</ul>
<p>
Example: An Account class declares <tt><a
href="ClassMethods.html#M001104">has_one</a> :beneficiary</tt>, which will
add:
</p>
<ul>
<li><tt>Account#beneficiary</tt> (similar to <tt>Beneficiary.find(:first,
:conditions =&gt; &quot;account_id = #{id}&quot;)</tt>)

</li>
<li><tt>Account#beneficiary=(beneficiary)</tt> (similar to
<tt>beneficiary.account_id = account.id; beneficiary.save</tt>)

</li>
<li><tt>Account#beneficiary.nil?</tt>

</li>
<li><tt>Account#build_beneficiary</tt> (similar to
<tt>Beneficiary.new(&quot;account_id&quot; =&gt; id)</tt>)

</li>
<li><tt>Account#create_beneficiary</tt> (similar to <tt>b =
Beneficiary.new(&quot;account_id&quot; =&gt; id); b.save; b</tt>)

</li>
</ul>
<p>
The declaration can also include an options hash to specialize the behavior
of the association.
</p>
<p>
Options are:
</p>
<ul>
<li><tt>:class_name</tt> - specify the class name of the association. Use it
only if that name can&#8216;t be inferred from the association name. So
<tt><a href="ClassMethods.html#M001104">has_one</a> :manager</tt> will by
default be linked to the <tt>Manager</tt> class, but if the real class name
is <tt>Person</tt>, you&#8216;ll have to specify it with this option.

</li>
<li><tt>:conditions</tt> - specify the conditions that the associated object
must meet in order to be included as a <tt>WHERE</tt> SQL fragment, such as
<tt>rank = 5</tt>.

</li>
<li><tt>:order</tt> - specify the order in which the associated objects are
returned as an <tt>ORDER BY</tt> SQL fragment, such as <tt>last_name,
first_name DESC</tt>

</li>
<li><tt>:dependent</tt> - if set to <tt>:destroy</tt>, the associated object is
destroyed when this object is. If set to <tt>:delete</tt>, the associated
object is deleted <b>without</b> calling its destroy method. If set to
<tt>:nullify</tt>, the associated object&#8216;s foreign key is set to
<tt>NULL</tt>. Also, association is assigned.

</li>
<li><tt>:foreign_key</tt> - specify the foreign key used for the association.
By default this is guessed to be the name of this class in lower-case and
<tt>_id</tt> suffixed. So a <tt>Person</tt> class that makes a <tt><a
href="ClassMethods.html#M001104">has_one</a></tt> association will use
<tt>person_id</tt> as the default <tt>foreign_key</tt>.

</li>
<li><tt>:include</tt> - specify second-order associations that should be eager
loaded when this object is loaded.

</li>
<li><tt>:as</tt>: Specifies a polymorphic interface (See <tt><a
href="ClassMethods.html#M001105">belongs_to</a></tt>).

</li>
</ul>
<p>
Option examples:
</p>
<pre>
  has_one :credit_card, :dependent =&gt; :destroy  # destroys the associated credit card
  has_one :credit_card, :dependent =&gt; :nullify  # updates the associated records foreign key value to NULL rather than destroying it
  has_one :last_comment, :class_name =&gt; &quot;Comment&quot;, :order =&gt; &quot;posted_on&quot;
  has_one :project_manager, :class_name =&gt; &quot;Person&quot;, :conditions =&gt; &quot;role = 'project_manager'&quot;
  has_one :attachment, :as =&gt; :attachable
</pre>
          <p><a class="source-toggle" href="#"
            onclick="toggleCode('M001104-source');return false;">[Source]</a></p>
          <div class="method-source-code" id="M001104-source">
<pre>
     <span class="ruby-comment cmt"># File vendor/rails/activerecord/lib/active_record/associations.rb, line 726</span>
726:       <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">has_one</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span> = {})
727:         <span class="ruby-identifier">reflection</span> = <span class="ruby-identifier">create_has_one_reflection</span>(<span class="ruby-identifier">association_id</span>, <span class="ruby-identifier">options</span>)
728: 
729:         <span class="ruby-identifier">module_eval</span> <span class="ruby-keyword kw">do</span>
730:           <span class="ruby-identifier">after_save</span> <span class="ruby-value str">&quot;association = instance_variable_get(\&quot;@\#{reflection.name}\&quot;)\nif !association.nil? &amp;&amp; (new_record? || association.new_record? || association[\&quot;\#{reflection.primary_key_name}\&quot;] != id)\nassociation[\&quot;\#{reflection.primary_key_name}\&quot;] = id\nassociation.save(true)\nend\n&quot;</span>
731:         <span class="ruby-keyword kw">end</span>
732:       
733:         <span class="ruby-identifier">association_accessor_methods</span>(<span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasOneAssociation</span>)
734:         <span class="ruby-identifier">association_constructor_method</span>(<span class="ruby-identifier">:build</span>,  <span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasOneAssociation</span>)
735:         <span class="ruby-identifier">association_constructor_method</span>(<span class="ruby-identifier">:create</span>, <span class="ruby-identifier">reflection</span>, <span class="ruby-constant">HasOneAssociation</span>)
736:         
737:         <span class="ruby-identifier">configure_dependency_for_has_one</span>(<span class="ruby-identifier">reflection</span>)
738:       <span class="ruby-keyword kw">end</span>
</pre>
          </div>
        </div>
      </div>


    </div>


  </div>


<div id="validator-badges">
  <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p>
</div>

</body>
</html>